<template>
	<view class="goods-list">
		<view v-for="(item,index) in goodsList" :key="index" @click="gotoDetail(item)">
			<!-- 为 my-goods 组件动态绑定 goods 属性的值 -->
			<my-goods :goods="item"></my-goods>
		</view>
	</view>
</template>

<script>
	import goodsAPI from '../../api/goodsAPI.js'
	export default {
		data() {
			return {
				// 请求参数对象
				queryObj: {
					// 查询关键词
					query: '',
					// 商品分类Id
					cid: '',
					// 页码值
					pagenum: 1,
					// 每页显示多少条数据
					pagesize: 10
				},
				// 商品列表的数据
				goodsList: [],
				// 是否正在请求数据
				isloading: false,
				// 查询结果的总记录数
				total: 0,
				// 默认的空图片
				defaultPic: 'https://img3.doubanio.com/f/movie/8dd0c794499fe925ae2ae89ee30cd225750457b4/pics/movie/celebrity-default-medium.png'

			};
		},
		onLoad(options) {
			this.queryObj.cid = options.cid || ''
			this.queryObj.query = options.query || ''
			console.log('options', options.cid);
			this.getGoodsList()
		},
		methods: {
			async getGoodsList(isDown) {
				console.log('queryObj', this.queryObj);
				const totalPage = this.total % this.queryObj.pagesize === 0 ?
					this.total / this.queryObj.pagesize : this.total / this.queryObj.pagesize + 1
				// 判断是否还有下一页数据
				if (this.total !== 0 && this.queryObj.pagenum > totalPage) {
					return uni.$showMsg('数据加载完毕！')
				}
				// ** 打开节流阀
				this.isloading = true

				const {
					data: res
				} = await goodsAPI.searchGoods(this.queryObj)

				// const {
				// 	data: res
				// } = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)

				if (isDown) {
					this.goodsList = [...res.message.goods, ...this.goodsList]
					uni.stopPullDownRefresh()
				} else {
					this.goodsList = [...this.goodsList, ...res.message.goods]
				}
				if (res.meta.status !== 200) return uni.$showMsg()
				// ** 关闭节流阀
				this.isloading = false

				this.total = res.message.total

				console.log('res==', res);
			},
			// 上拉触底事件
			onReachBottom() {
				console.log('上拉触底事件...');

				//page++
				this.queryObj.pagenum++

				//重新查询数据
				this.getGoodsList(false)
			},
			//下拉刷新
			onPullDownRefresh() {
				console.log('下拉刷新事件....');

				this.queryObj.pagenum++
				this.getGoodsList(true)
			},
			// 点击列表项，转到商品详情列表
			gotoDetail(item) {
				console.log('clicked...', item);
				uni.navigateTo({
					url: '/pages/goods_detail/main?goods_id=' + item.goods_id

				})
			}
		}
	}
</script>

<style lang="scss">
	.goods-item {
		display: flex;
		padding: 10px 5px;
		border-bottom: 1px solid #f0f0f0;

		.goods-item-left {
			margin-right: 5px;

			.goods-pic {
				width: 100px;
				height: 100px;
				display: block;
			}
		}

		.goods-item-right {
			display: flex;
			flex-direction: column;
			justify-content: space-between;

			.goods-name {
				font-size: 13px;
			}

			.goods-price {
				font-size: 16px;
				color: #c00000;
			}
		}
	}
</style>